const cloud = require('wx-server-sdk');
const axios = require('axios');

cloud.init();

// 微软 Azure 配置
const subscriptionKey = 'YOUR_AZURE_KEY';
const region = 'eastasia';

exports.main = async (event, context) => {
  try {
    // 获取访问令牌
    const tokenResponse = await axios.post(
      `https://${region}.api.cognitive.microsoft.com/sts/v1.0/issueToken`,
      null,
      {
        headers: {
          'Ocp-Apim-Subscription-Key': subscriptionKey,
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }
    );

    const accessToken = tokenResponse.data;

    // 文本转语音
    const response = await axios.post(
      `https://${region}.tts.speech.microsoft.com/cognitiveservices/v1`,
      `<speak version='1.0' xml:lang='en-US'>
        <voice xml:lang='en-US' xml:gender='Female' name='en-US-JennyNeural'>
          ${event.text}
        </voice>
      </speak>`,
      {
        headers: {
          'Authorization': `Bearer ${accessToken}`,
          'Content-Type': 'application/ssml+xml',
          'X-Microsoft-OutputFormat': 'audio-16khz-128kbitrate-mono-mp3'
        },
        responseType: 'arraybuffer'
      }
    );

    // 将音频数据转换为 base64
    const audioBase64 = Buffer.from(response.data).toString('base64');
    
    return {
      audio: `data:audio/mp3;base64,${audioBase64}`
    };
  } catch (error) {
    console.error(error);
    throw error;
  }
}; 